package com.hsy.baseTest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;
import java.util.List;

public class ShiroTest {

    public ShiroTest() {
        //创建安全管理器
        DefaultSecurityManager manager = new DefaultSecurityManager();
        //设置权限认证数据来源，为类路径下shiro.ini
        manager.setRealm(new CustomRealm());
        //设置安全管理器
        SecurityUtils.setSecurityManager(manager);
        //得到主体
        Subject subject = SecurityUtils.getSubject();
        //产生用户名和密码的令牌
        UsernamePasswordToken token = new UsernamePasswordToken("tom","111");
        //登录认证
        try {
            subject.login(token);
            System.err.println("登陆成功");
            //查看当前用户是否具有manager角色
//            System.err.println(subject.hasRole("manager"));
//            //查看当前用户是否同时具有manager和order两个角色
//            System.err.println(subject.hasAllRoles(List.of("manager","order")));
//
//            //查看当前用户是否具有指定权限
//            System.err.println(subject.isPermitted("user:create"));
//            System.err.println(subject.isPermitted("user:delete"));

            //查看当前用户是否同时具有指定权限
            System.err.println(subject.isPermittedAll("user:create", "order:add"));
        }catch (UnknownAccountException e1){
            System.err.println("账号异常");;
        }catch (IncorrectCredentialsException e2){
            System.err.println("密码错误");
        }
    }

    public static void main(String[] args) {
        new ShiroTest();
    }
}
